<script setup>
import { ref, inject, onMounted } from "vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";

const axios = inject("axios");

onMounted(() => {
  fetchData(page.value, pageSize.value);
});

const page = ref(1);
const pageSize = ref(10);
const tableData = ref([]);
const total = ref(0);
const isModelOpen = ref(false);
const isModelStatus = ref("");
const formData = ref({
  userId: null,
  describe: "",
  username: "",
  status: 0,
});

const fetchData = async (page, pageSize) => {
  const res = await axios.get(`/admin/users`, {
    params: {
      page: page,
      pageSize: pageSize,
    },
  });
  tableData.value = res.data.data.record;
  total.value = res.data.data.total;
};

const handlePageChange = (newPage) => {
  page.value = newPage;
  fetchData(page.value, pageSize.value);
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchData(page.value, pageSize.value);
};

const handleOpenModel = (row) => {
  console.log(row);
  formData.value = { userId: null, username: "", describe: "" };
  isModelStatus.value = "add";
  if (row) {
    console.log(row);
    formData.value = { ...row };
    isModelStatus.value = "edit";
  }
  isModelOpen.value = true;
};

const handleDelete = async (userId) => {
  const res = await axios.delete(`/admin/user/${userId}`);
  if (res.data.code === 200) {
    fetchData(page.value, pageSize.value);
    ElMessage.success("删除成功");
  } else {
    ElMessage.error("删除失败");
  }
};

const handleOk = async () => {
  console.log("formdata", formData.value);
  if (isModelStatus.value === "edit") {
    const res = await axios.put(`/admin/user`, formData.value);
    if (res.data.code === 200) {
      ElMessage.success("修改成功");
      fetchData(page.value, pageSize.value);
      handleCancel();
    } else {
      ElMessage.error("修改失败");
    }
  } else {
    const res = await axios.post(`/admin/tag`, formData.value);
    console.log(res.data);
    if (res.data.code === 200) {
      ElMessage.success("添加成功");
      fetchData(page.value, pageSize.value);
      handleCancel();
    } else {
      ElMessage.error("添加失败");
    }
  }
};

const updateUserPassword = async (userId) => {
  const res = await axios.put(`/admin/user`, {
    userId: userId,
    password: "123456",
  });
  console.log("res", res.data);
  if (res.data.code === 200) {
    ElMessage.success("修改成功");
    fetchData(page.value, pageSize.value);
    handleCancel();
  } else {
    ElMessage.error("修改失败");
  }
};

const handleCancel = () => {
  isModelOpen.value = false;
  formData.value = { userId: null, tagName: "", describe: "" };
  isModelStatus.value = "";
};
</script>

<template>
  <el-button
    type="success"
    plain
    @click="handleOpenModel()"
    style="margin-left: auto; margin-right: 72px"
    >新增用户</el-button
  >

  <!-- 新增和编辑的表单 -->
  <el-dialog
    :title="isModelStatus === 'edit' ? '编辑用户' : '新增用户'"
    v-model="isModelOpen"
    width="500"
  >
    <el-form ref="formRef" :model="formData" label-width="auto">
      <el-form-item label="用户名">
        <el-input v-model="formData.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="个性签名" v-if="isModelStatus === 'edit'">
        <el-input
          v-model="formData.describe"
          placeholder="请输入用户个性签名"
        />
      </el-form-item>
      <el-form-item label="账号" v-if="isModelStatus === 'add'">
        <el-input v-model="formData.account" placeholder="请输入用户账号" />
      </el-form-item>
      <el-form-item label="密码" v-if="isModelStatus === 'add'">
        <el-input
          v-model="formData.password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="用户状态：" v-if="isModelStatus === 'edit'">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="3">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleOk">确定</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </template>
  </el-dialog>

  <el-table
    :data="tableData"
    style="width: 95%"
    max-height="530"
    :header-cell-style="{ 'text-align': 'center' }"
    :cell-style="{ 'text-align': 'center' }"
  >
    <el-table-column prop="userId" label="用户id" width="100" sortable />
    <el-table-column prop="account" label="账号" width="120" sortable />
    <el-table-column prop="username" label="用户名" width="120" sortable />
    <el-table-column prop="describe" label="描述" width="120" sortable />
    <el-table-column label="用户状态" width="180" sortable>
      <template #default="scope">
        <el-tag v-if="scope.row.status === 1" type="success" size="small">
          正常
        </el-tag>
        <el-tag v-else-if="scope.row.status === 2" type="warning" size="small">
          待审核
        </el-tag>
        <el-tag v-else-if="scope.row.status === 3" type="danger" size="small">
          禁用
        </el-tag>
        <el-tag v-else size="small">未知</el-tag></template
      >
    </el-table-column>
    <el-table-column label="创建时间">
      <template #default="prop">
        {{ dayjs(prop.row.createdAt).format("YYYY年MM月DD日 HH:mm") }}
      </template>
    </el-table-column>
    <el-table-column label="更新时间">
      <template #default="prop">
        {{ dayjs(prop.row.updatedAt).format("YYYY年MM月DD日 HH:mm") }}
      </template>
    </el-table-column>
    <el-table-column prop="options" label="操作" width="300">
      <template #default="prop">
        <el-button type="primary" plain @click="handleOpenModel(prop.row)"
          >编辑</el-button
        >
        <el-popconfirm
          title="确定要删除该重置用户密码吗？ 重置后为123456"
          placement="top-start"
          confirm-button-text="确定"
          cancel-button-text="取消"
          @confirm="updateUserPassword(prop.row.userId)"
        >
          <template #reference>
            <el-button type="success" plain>重置密码</el-button>
          </template>
        </el-popconfirm>
        <el-popconfirm
          title="确定要删除该用户吗？"
          placement="top-start"
          confirm-button-text="确定"
          cancel-button-text="取消"
          @confirm="handleDelete(prop.row.userId)"
        >
          <template #reference>
            <el-button type="danger" plain>删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    style="display: flex; justify-content: center; margin-top: 15px"
    :page-size="pageSize"
    :default-page-size="page"
    :page-sizes="[10, 20, 50, 100]"
    page-sizes
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handlePageChange"
  />
</template>

<style scoped></style>
